import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {OneOperationComponent} from '../../../widgets/one-operation/one-operation.component';
import {PageSubject} from '../../../util/page-subject';
import {TableUtil} from '../../../util/table-util';
import {ResponseUtil} from '../../../util/response-util';
import {DataAuditAdjustService} from './data-audit-adjust.service';
import {MsgConstants} from '../../../constants/constants';
import {OneDialogService} from '../../../widgets/one-dialog/one-dialog.service';
import {DataAuditAPI, DataRouteUrl} from '../data-audit-constants';

declare var moment;
declare var $;

@Component({
  selector: 'app-data-audit-adjust',
  templateUrl: './data-audit-adjust.component.html',
  styleUrls: ['./data-audit-adjust.component.css']
})
export class DataAuditAdjustComponent implements OnInit, AfterViewInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;
  proxy = {
  };

  table: any;
  dataSourceId = '';

  tableHeadArr: Array<any> = [];
  testTableData: Array<any> = [];
  sourceHeadObj: any = {};

  dataSourceArr: Array<any> = [];

  startDate: Date = new Date(moment().subtract(1, 'M').format('YYYY-MM-DD'));
  endDate: Date = new Date();

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private pageSubject: PageSubject,
    private responseUtil: ResponseUtil,
    private tableUtil: TableUtil,
    private dialogService: OneDialogService,
    private adjustService: DataAuditAdjustService,
  ) { }

  ngOnInit() {
    this.pushPage();
    this.initData();
    this.getDataSource()
  }
  ngAfterViewInit() {
    // 操作函数代理
    this.operation.proxy = this.proxy;
  }
  /**
   * 面包屑导航
   */
  pushPage() {
    // const path = new Path('数据校正', '');
    this.pageSubject.pushPage('审核数据', '查询');
  }

  /**
   * 初始化数据
   */
  initData = () => {
  };

  /**
   * 加载表格
   */
  loadAdjust() {
    this.table = this.tableUtil.load('one_table_data-adjust',  {
      columns: this.addColumns(),
      idField: 'id',
      sidePagination: 'server',
      pagination: '1',
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 15, 50],
      paginationPreText: '上一页',
      paginationNextText: '下一页',
      paginationLoop: false, // 是否开启循环分页
      singleSelect: false, // 多选
      clickToSelect: '1', // 点击选中
      toolbar: '#one_operation_data-adjust',
      // data: this.testTableData,
      url: DataAuditAPI.getAuditData,
      method: 'get',
      // 传递附加参数
      queryParams: (params) => {
        params.dsConfId = this.dataSourceId;
        params.type = '1';
        params.startTime = moment(this.startDate).format('YYYY-MM-DD 00:00:00');
        params.endTime = moment(this.endDate).format('YYYY-MM-DD 23:59:59');
        return params;
      },
      // 返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, () => {

        });
      },
      height: 700, // table高度
      sortable: '1',
      order: 'asc',
      classes: 'table table-hover',
      striped: '1', // 隔行变色
      mobileResponsive: '1', // 响应式
      showColumns: '1', // 显示自定义显示列按钮
      showRefresh: '1', // 显示刷新按钮
      minimumCountColumns: 0, // 最少保留显示的列数量
      showToggle: '1', // 显示视图切换按钮
      showPaginationSwitch: '1', // 显示是否分页切换按钮
      onPostBody: () => {
      }
    });
  }

  /**
   * 添加表头
   */
  addColumns = () => {
    const colArr: Array<any> = [];
    colArr.push({
      field: 'oper',
      title: '操作',
      align: 'center',
      valign: 'middle',
      formatter: this.addAudit,
      events:
        {
          'click .audit': this.auditRowData,
          'click .valid': this.validRowData
        }
    });
    this.tableHeadArr.forEach((val, i) => {
      val.index = i;
      const colObj: any = {
        field: val.code,
        title: val.name,
        align: 'center',
        valign: 'middle',
        visible: val.isVisiable === '1',
        switchable: val.isVisiable === '1',
        events:
          {
            // 'click .clearData': (e, value, row, index) => {
            //   this.clearColData(e, value, row, index, val.code)
            // },
            'click .invalid': (e, value, row, index) => {
              this.invalidData(e, value, row, index, val.code)
            },
            'input .dataChange': (e, value, row, index) => {
              if (val.type !== '4') {
                this.changeColData(e, value, row, index, val)
              }
            },
            'blur .dataChange': (e, value, row, index) => {
              if (val.type !== '4') {
                this.blurUpdateData(e, value, row, index, val)
              }
            }
          }
      };
      if (val.isAudit === '1') {
        colObj.formatter = (value, row, index) => {
          return this.addOpreaAduit(value, row, index, val)
        }
      } else {
        colObj.formatter = (value, row, index) => {
          return value || '-'
        }
      }
      colArr.push(colObj)
    });
    return colArr;
  };

  /**
   * 格式化函数
   * @param value
   * @param row
   * @param index
   * @param data
   * @returns {string}
   */
  private addOpreaAduit = (value, row, index, data) => {
    let auditHtml = '', validHtml = '', inputHtml = '';
    const dataObj = this.getFieldParentData(row, data.code);
    if (dataObj) {
      if (dataObj.isAudit) {
        auditHtml = '<span style="display: inline-block;width: 24px;white-space: pre-wrap; vertical-align: middle;font-size: 10px;margin-right: 5px;text-align: center;">已审核</span>';
      } else {
        // auditHtml = '<span style="font-size: 10px;margin-right: 10px;">未审核</span>';
      }
      if (dataObj.status) {
        validHtml = '<span class="fa fa-check" ' +
          'style="display: inline-block;width: 12px;font-size: 10px;margin-right: 3px;color: #48ab5d;"' +
          ' title="有效" data-toggle="tooltip"></span>';
      } else {
        validHtml = '<span class="fa fa-close" ' +
          'style="display: inline-block;width: 12px;font-size: 12px;margin-right: 3px;color: #ce2504;"' +
          ' title="无效" data-toggle="tooltip"></span>';
      }
      if ((row.hasOwnProperty('status') && !row.status) || !dataObj.status) {
        inputHtml = `
      <input type="text" readonly
           class="form-control dataChange ${data.type === '4' ? 'date' : ''}"
           data-field = '${data.code}' style="width: 60px;display: inline-block;"
           value="${value}"
           maxLength="${data.length}"
           />
      `
      } else {
        inputHtml = `
      <input type="text"
           class="form-control dataChange ${data.type === '4' ? 'date' : ''}"
           data-field = '${data.code}' style="width: 60px;display: inline-block;"
           value="${value}"
           maxLength="${data.length}"
           />
      `
      }
    }
    // <span class="fa fa-close"></span>
    // style="position: absolute;right: 3px;top: 7px;"
    // <a class="clearData">清空</a>
    return `
    <div style="min-width: 138px;">
      <div style="display: inline-block;width: 44px;text-align: right;color: #999;">
        ${auditHtml}${validHtml}</div>
      <div style="display: inline-block;min-width: 90px;">
        ${inputHtml}
        <a class="invalid" 
        style="display: inline-block;width: 24px;white-space: pre-wrap; vertical-align: middle;">${dataObj && dataObj.status ? '无效' : '有效'}</a>
       </div>
      </div>
    `
    /*
    * //   <div style="min-width: 125px">
    //      <input type="${data.type === '2' || data.type === '3' ? 'number' : 'text'}"
    //      class="form-control dataChange ${data.type === '4' ? 'date' : ''}"
    //      data-field = '${data.code}'
    //      style="display: inline-block;width: 50%;min-width: ${maxData}px;"
    //      maxLength="${data.length}" value="${value}" / >
    //      <a  class="clearData"><span class="fa fa-close"></span></a>
    // </div>*/
  };
  addAudit = (value, row, index) => {
    let validHtml = '<a  class="valid">无效</a>';
    if (row.hasOwnProperty('status')) {
      if (!row.status) {
        validHtml = '<a  class="valid">有效</a>'
      }
    }
    return `
      <div style="line-height: 32px;">
         <a  class="audit">审核</a>
         ${validHtml}
    </div>
    `
  };
  /**
   * 清空数据
   * */
  clearColData = (e, value, row, index, field) => {
    // value = this.getFieldParentData(row, field);
    // value.value = '';
    // this.table.bootstrapTable('updateRow', {index: index, row: row});
  };
  /**
   * 标记有效/无效数据
   * */
  invalidData = (e, value, row, index, field) => {
    if (row.hasOwnProperty('status') && !row.status) {
      this.dialogService.info('该条数据无效');
      return false;
    }
    value = this.getFieldParentData(row, field);
    if (value.status) {
      value.status = 0;
    } else {
      value.status = 1;
    }
    if (!value.isAudit) {
      value.isAudit = 1;
    }
    this.table.bootstrapTable('updateRow', {index: index, row: row});
  };
  /**
   * 输入框输入事件
   * */
  changeColData = (e, value, row, index, data) => {
    const fieldRexObj = this.fieldRex(data.type);
    const rex: RegExp = fieldRexObj.rex;
    let rexMsg = fieldRexObj.rexMsg;
    if (rex.test(e.target.value) || !e.target.value) {
    } else {
      this.dialogService.info(data.name + rexMsg);
    }
  };
  fieldRex = (type) => {
    let rex: RegExp = /^$/;
    let rexMsg = '';
    if (type === '2') {
      rex =  /^[1-9]\d*$/;
      rexMsg = '只能是正整数';
    } else  if (type === '3') {
      // rex =  /^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$/;
      rex =   /^[0-9]\d*(\.?)\d*$/;
      rexMsg = '只能是小数';
    } else {
      rex = /([\s\S]*)/;
      rexMsg = '格式不正确';
    }
    return {rex: rex, rexMsg: rexMsg}
  };
  /**
   * 输入框失去焦点事件
   * */
  blurUpdateData = (e, value, row, index, data) => {
    value = this.getFieldParentData(row, data.code);
    const fieldRexObj = this.fieldRex(data.type);
    const rex: RegExp = fieldRexObj.rex;
    let rexMsg = fieldRexObj.rexMsg;
    if (rex.test(e.target.value) || !e.target.value) {
      if (row.hasOwnProperty('formatErr')) {
        const index = row.formatErr.indexOf(data.name + rexMsg);
        if (index !== -1) {
          row.formatErr.splice(index, 1);
        }
        if (row.formatErr.length <= 0) {
          delete row.formatErr;
        }
      }
    } else {
      if (row.hasOwnProperty('formatErr') &&  row.formatErr.indexOf(data.name + rexMsg) === -1) {
        row.formatErr.push(data.name+ rexMsg);
      } else {
        row.formatErr = [data.name + rexMsg];
      }
    }
    let code: string;
    if (data.code) {
      const codeArr = data.code.split('.');
      code = codeArr[codeArr.length - 1];
    }
    value[code] = e.target.value;
    if (!value.isAudit) {
      value.isAudit = 1;
    }
    this.table.bootstrapTable('updateRow', {index: index, row: row});
  };
  /**
   * 标记整条无效
   */
  validRowData = (e, value, row, index) => {
    if (row.hasOwnProperty('status')) {
      if (row.status) {
        row.status = 0
      } else {
        row.status = 1
      }
    } else {
      row.status = 0
    };
    this.tableHeadArr.forEach((val, i) => {
      if (val.isAudit === '1') {
        const dataObj = this.getFieldParentData(row, val.code);
        if (!(dataObj instanceof Function) && dataObj instanceof Object) {
          dataObj.isAudit = 1;
        }
      }
    });
    this.table.bootstrapTable('updateRow', {index: index, row: row});
  };
  /**
   * 审核数据
   * */
  auditRowData = (e, value, row, index) => {
    if (row.hasOwnProperty('formatErr')) {
      this.dialogService.info(row.formatErr.join(' , ') + ' ,请修改后再进行审核');
      return false;
    }
    this.dialogService.modalInfoWithCancelBtn('审核后数据不可进行修改，确定审核数据？', () => {
      this.postAuditData(row);
    }, () => {
    });
    // const auditData = JSON.parse(JSON.stringify(row));
    // const auditDataArr: Array<any> = [];
    // for (const key in auditData.factors) {
    //   const obj = auditData.factors[key];
    //   obj.code = key;
    //   auditDataArr.push(obj)
    // }
    // row.factors = auditDataArr;
  };

  /**
   * 审核数据
   */
  postAuditData = (data) => {
    if (!data.hasOwnProperty('status')) {
      data.status = 1;
    }
    const dataObj = {
      dsConfId: this.dataSourceId,
      data: JSON.stringify(data)
    };
    this.adjustService.postAuditData(dataObj).subscribe(
      result => this.responseUtil.success(result, this.handleAuditData),
      error => this.responseUtil.error(error)
    )
  };
  handleAuditData = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.dialogService.success('审核数据成功');
      this.search();
    } else {
      this.dialogService.info(result.message);
    }
  };
  search() {
    this.tableUtil.refreshOptions({columns: this.addColumns(),pageNumber: 1});
  }

  /**
   * 跳转至数据生成页面
   */
  jumpToGene () {
    this.router.navigate([DataRouteUrl.geneUrl], {relativeTo: this.route})
  }
  /*
  * 获取field数据
  * */
  getFieldParentData = (value, field) => {
    const props = field.split('.');
    for (const p in props) {
      if (props.hasOwnProperty(p) && parseFloat(p) !== (props.length - 1)) {
        value = value && value[props[p]];
      }
    }
    return value;
  };
  /**
   * 获取表格表头数据
   */
  getTableHeadData = () => {
    const dataObj = {
      limit: 10,
      order: 'asc',
      offset: 0,
      type: '1',
      // tableDataType: 'tableHead',
      dsConfId: this.dataSourceId,
      startTime: this.startDate ? moment(this.startDate).format('YYYY-MM-DD HH:00:00') : '',
      endTime: this.endDate ? moment(this.endDate).format('YYYY-MM-DD 23:59:59') : ''
    };
    this.adjustService.getTableHeadData(dataObj).subscribe(
      result => this.responseUtil.success(result, this.handleHeadData),
      error => this.responseUtil.error(error)
    )
  };
  handleHeadData = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.nameList.length > 0) {
        this.tableHeadArr = result.data.nameList;
        this.sourceHeadObj[this.dataSourceId] = result.data.nameList;
      }
      if (this.table) {
        this.search();
      } else {
        this.loadAdjust();
      }
    } else {
      this.dialogService.info(result.message);
    }
  };
  changDataSource = (isOpen) =>{
    if (!isOpen) {
      if (!this.sourceHeadObj.hasOwnProperty(this.dataSourceId)) {
        this.getTableHeadData();
      } else {
        this.tableHeadArr = this.sourceHeadObj[this.dataSourceId];
        this.search();
      }
    }
  };

  /**
   * 获取数据源
   */
  getDataSource = () => {
    this.adjustService.getDataSource().subscribe(
      result => this.responseUtil.success(result, this.handleDataSource),
      error => this.responseUtil.error(error)
    )
  };
  handleDataSource = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        this.dataSourceArr = result.data;
        this.dataSourceId = this.dataSourceArr[0].id;
        this.getTableHeadData();
      }
    } else {
      this.dialogService.info(result.message);
    }
  };
  /**
   * 开始时间、结束时间
   */
  startValueChange = () => {
    if (this.startDate > this.endDate) {
      this.endDate = null;
    }
  };
  endValueChange = () => {
    if (this.startDate > this.endDate) {
      this.startDate = null;
    }
  };
  disabledStartDate = (startValue) => {
    if (!startValue || !this.endDate) {
      return false;
    }
    return startValue.getTime() > this.endDate.getTime();
  };
  disabledEndDate = (endValue) => {
    if (!endValue || !this.startDate) {
      return false;
    }
    return endValue.getTime() < this.startDate.getTime();
  };
}
